<?php

namespace Encore\MediaManagerSelect\Http\Controllers;

use Encore\Admin\Layout\Content;
use Encore\Admin\Media\MediaManager;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

class MediaManagerSelectController extends Controller
{
    public function index(Content $content)
    {
        return $content
            ->title('Title')
            ->description('Description')
            ->body(view('media-manager-select::index'));
    }

    /**
     * 媒体目录和列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request)
    {
        $path = $request->get('path', '/');

        $manager = new MediaManager($path);
        $list    = $manager->ls();
        foreach ($list as $k => $v) {
            $list[$k]['base_name'] = basename($v['name']);
            $v['isDir'] && $list[$k]['preview'] = "<a><span class=\"file-icon text-aqua\"><i class=\"fa fa-folder\"></i></span></a>";
        }

        return response()->json([
                                    'status' => true,
                                    'data'   => [
                                        'list' => $list,
                                        'nav'  => $this->navigation($path),
                                        'url'  => $manager->urls(),
                                    ],
                                ]);
    }

    public function navigation($origin_path)
    {
        $folders = explode('/', $origin_path);

        $folders = array_filter($folders);

        $path = '';

        $navigation = [];

        foreach ($folders as $folder) {
            $path = rtrim($path, '/') . '/' . $folder;

            $navigation[] = [
                'name' => $folder,
                'url'  => $path . '/',
            ];
        }

        return $navigation;
    }
}
